<template>
  <a-card style="margin-top:-2px" :bordered="false">
    <div class="">
      <a-form :form="form" v-show="!nextShow">
        <a-row class="form-row" >
          <a-col :span="10" :offset="1">
            <a-form-item
              label="代码名称"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol">
              <a-input
                style="width:260px"
                v-decorator="[
                  'gName',
                  { rules: [{ required: true, message: '请填写代码名称!' }] },
                ]" />
            </a-form-item>
          </a-col>
          <a-col :span="10" :offset="1">
            <a-form-item
              label="数据库"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol">
              <a-select
                placeholder="请选择"
                style="width:260px"
                v-decorator="[
                  'dataBase',
                  { rules: [{ required: true, message: '请选择数据库!' }] },
                ]"
                @change="dataBaseChange"
              >
                <a-select-option v-for="item in dataBaseInfo" :key="item.id" :value="item.id" >{{ item.dbName }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" >
          <a-col :span="10" :offset="1">
            <a-form-item
              label="配置信息"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol">
              <a-select
                placeholder="请选择"
                style="width:260px"
                v-decorator="[
                  'config',
                  { rules: [{ required: true, message: '请选择配置信息!' }] },
                ]"
                @change="configChange"
              >
                <a-select-option v-for="item in configInfo" :key="item.id" :value="item.id" >{{ item.cname }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="10" :offset="1">
            <a-form-item
              label="JAVA路径"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol">
              <a-input
                style="width:260px"
                v-decorator="[
                  'javaPath',
                  { rules: [{ required: true, message: '请填写JAVA路径!' }] },
                ]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" >
          <a-col :span="10" :offset="1">
            <a-form-item
              label="VUE路径"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol">
              <a-input
                style="width:260px"
                v-decorator="[
                  'vuePath',
                  { rules: [{ required: true, message: '请填写VUE路径!' }] },
                ]"/>
            </a-form-item>
          </a-col>
          <a-col :span="10" :offset="1">
            <a-form-item
              label="服务名称"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol">
              <a-input
                style="width:260px"
                v-decorator="[
                  'serverName',
                  { rules: [{ required: true, message: '请填写服务名称!' }] },
                ]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" >
          <a-col :span="10" :offset="1">
            <a-form-item
              label="模块名称"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol">
              <a-input
                style="width:260px"
                v-decorator="[
                  'moduleName',
                  { rules: [{ required: true, message: '请填写模块名称!' }] },
                ]"/>
            </a-form-item>
          </a-col>
          <a-col :span="10" :offset="1">
            <a-form-item
              label="生成类型"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol">
              <a-radio-group
                buttonStyle="solid"
                @change="generationTypeChange"
                v-decorator="[
                  'generationType',
                  { rules: [{ required: true, message: '请选择生成类型!' }] },
                ]">
                <a-radio-button value="one">单表查询</a-radio-button>
                <a-radio-button value="some">多表查询</a-radio-button>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row style="margin-top:10px;margin-left:90px;">
          <a-col>
            <a-checkbox-group @change="onCheckBoxChange">
              <a-checkbox style="margin-left:20px;" value="export">导出</a-checkbox>
              <a-checkbox style="margin-left:20px;" value="add">新增</a-checkbox>
              <a-checkbox style="margin-left:20px;" value="del">删除</a-checkbox>
              <a-checkbox style="margin-left:20px;" value="upd">修改</a-checkbox>
            </a-checkbox-group>
          </a-col>
        </a-row>
        <a-row style="margin-top:10px">
          <a-col v-show="generationTypeIf">
            <a-form-item
              style="margin-left:90px;"
              label=""
            >
              <a-textarea
                style="width:890px"
                v-decorator="['sql', { rules: [{ required: true, message: '请输入SQL!' }] }]"
                placeholder="请输入SQL"
                :rows="10"
                :cols="200"/>
            </a-form-item>
          </a-col>
          <a-col v-show="!generationTypeIf">
            <a-form-item
              style="margin-left:90px;"
              label=""
            >
              <a-radio-group
                name="radioGroup"
                v-decorator="['tableName', { rules: [{ required: false, message: '请选择表' }] }]">
                <a-radio
                  style="margin-left:15px"
                  v-for="item in tables"
                  :value="item.tableName"
                  :key="item.tableName">{{ item.tableName }}</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <a-form >
        <a-row style="margin-top:5px" v-show="nextShow">
          <a-col >
            <s-table
              ref="stable"
              size="default"
              :columns="columns"
              :data="loadData"
              style="margin-top:10px"
            >
              <!--字段设置 -->
              <template slot="columnName" slot-scope="text,record,index">
                <a v-if="record.queryIf" herf="#" @click="columnConfig(index, record,text)">字段设置&nbsp;&nbsp;</a>
                <span >{{ text }}</span>&nbsp;
              </template>
              <!--字段显示名称 -->
              <template slot="comments" slot-scope="text,record,index">
                <editable-cell style="width:140px" :text="text" @change="onCellChange(index, $event)"/>
              </template>
              <!--是否为查询条件复选框 -->
              <span slot="queryIf" slot-scope="text,record,index">
                <a-checkbox
                  name="queryIf"
                  @change="queryCheck(index,$event)"
                >
                </a-checkbox>
              </span>
              <!-- 是否列表显示复选框-->
              <span slot="listIf" slot-scope="text,record,index">
                <a-checkbox
                  @change="listCheck(index,$event,record)"
                  :checked="record.listIf"
                >
                </a-checkbox>
              </span>
            </s-table>
          </a-col>
        </a-row>
        <!--下一步 -->
        <a-row style="margin-top:5px" >
          <a-col >
            <span >
              <a-button type="primary" style="margin-left: 500px;" v-if="!nextShow" @click="next('1')" >下一步</a-button>
              <a-button type="primary" style="margin-left: 500px;" v-if="nextShow" @click="next('2')" >代码生成</a-button>
              <a-button type="primary" style="margin-left: 10px;" v-if="nextShow" @click="next('3')" >返回</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 弹出框 -->
    <a-modal
      title="字段设置"
      style="top: 150px;"
      :width="950"
      v-model="columnVisible"
      @ok="handleOk"
      :destroyOnClose="true"
      :confirmLoading="confirmLoading"
    >
      <a-form :form="modalform">
        <a-row class="form-row" >
          <a-col :span="10" :offset="1">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="字段名称" >
              <a-input v-model="columnsConfig.columnName" disabled/>
            </a-form-item>
          </a-col>
          <a-col :span="10" :offset="1">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="字段类型" >
              <a-input v-model="columnsConfig.dataType" disabled/>
            </a-form-item>
          </a-col>
          <a-col :span="10" :offset="1">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="字段长度" >
              <a-input v-model="columnsConfig.dataLength" disabled/>
            </a-form-item>
          </a-col>
          <a-col :span="10" :offset="1">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="字段备注" >
              <a-input v-model="columnsConfig.comments" disabled/>
            </a-form-item>
          </a-col>
          <a-col :span="10" :offset="1">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="查询条件类型" >
              <a-select
                placeholder="请选择"
                v-model="columnsConfig.columnQueryType"
              >
                <a-select-option key="text" value="text" >文本</a-select-option>
                <a-select-option key="text" value="date" >日期</a-select-option>
                <a-select-option key="text" value="select" >下拉框</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="10" :offset="1" v-if="columnsConfig.columnQueryType=='select'">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="下拉框数据源" >
              <a-input
                placeholder="codelist视图中的Name值"
                v-model="columnsConfig.selectSource"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </a-card>
</template>
<script >
import { STable } from '@/components'
import { query, download } from '@/api/admin'
import EditableCell from '@/components/table/EditableCell'
export default {
  components: {
    STable, EditableCell
  },
  data () {
    return {
      // 响应式布局
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16, offset: 1 }
      },
      form: this.$form.createForm(this, { name: 'generation' }),
      modalform: this.$form.createForm(this, { name: 'modalform' }),
      dataBase: '', // 数据库
      dataBaseInfo: {}, // 数据库下拉列表
      config: '', // 配置信息
      configInfo: {}, // 配置信息下拉列表
      sqlInfo: '', // SQL信息
      generationInfo: {}, // 代码生成信息集合
      nextShow: false, // 页面显示
      columnVisible: false, // 字段页面设置 是否显示
      allMsg: {}, // 页面全部信息集合，用于代码生成
      generationTypeIf: false, // 生成类型是否显示
      tables: [], // 单表查询集合
      methods: [], // 生成包含方法,默认包含查询方法
      actionParam: {}, // 请求参数
      confirmLoading: false, // 弹出框loading
      columnsConfig: {}, // 设置字段的信息
      columnConfigIndex: 0, // 字段设置对应行号
      loadData: parameter => {
        if (parameter.gName === 'undefined' || parameter.gName === undefined) {
          return []
        }
        return query('/generator/code/generatormd/tableInfo', 'POST', {}, parameter)
          .then(res => {
            return res.result
          })
      },
      // 表头
      columns: [
        { title: '字段', dataIndex: 'columnName', scopedSlots: { customRender: 'columnName' } },
        { title: '字段类型', dataIndex: 'dataType' },
        { title: '字段长度', dataIndex: 'dataLength' },
        { title: '显示名称', dataIndex: 'comments', scopedSlots: { customRender: 'comments' } },
        { title: '查询条件', width: '200px', dataIndex: 'queryIf', scopedSlots: { customRender: 'queryIf' } },
        { title: '列表显示', width: '200px', dataIndex: 'listIf', scopedSlots: { customRender: 'listIf' } }
      ]
    }
  },
  created () {
    // 加载数据库下拉列表
    this.getDBInfo().then((res) => {
      this.dataBaseInfo = res.data
    })
    // 加载配置信息下拉列表
    this.getConfigInfo().then((res) => {
      this.configInfo = res.data
      // 初始化数据
      this.initData()
    })
  },
  methods: {
    // 初始化数据
    initData () {
      // 测试数据
      this.form.setFieldsValue({
        gName: '测试代码生成',
        serverName: 'generator',
        moduleName: 'test',
        dataBase: '9AJtUbXi',
        generationType: 'one',
        config: 'SsPasAiX',
        sql: 'select id, project_id, c_name, java_path, vue_path, module, flag, crt_user, crt_time, crt_name, crt_host, upd_time, upd_user, upd_name, upd_host, attr1, attr2, attr3, attr4 from t_config_info'
      })
      this.configChange('SsPasAiX')
      this.dataBaseChange('9AJtUbXi')
    },
    // 获取数据库信息
    getDBInfo () {
      return query('/generator/code/databasemd/allCondition?flag=1', 'GET', {}, {})
        .then(res => {
          return res.result
        })
    },
    // 获取配置信息
    getConfigInfo () {
      return query('/generator/code/configmd/allCondition?flag=1', 'GET', {}, {})
        .then(res => {
          return res.result
        })
    },
    // 下一步，获取字段信息
    next (value) {
      // 必填校验
      this.form.validateFields((err, values) => {
        var generationType = this.form.getFieldValue('generationType')// 判断是单表 还是SQL
        if (value === '1') { // 下一步
          if (!err) {
            if (generationType === 'some') { // 如果是多表
              this.generationInfo = this.form.getFieldsValue()// 获取配置信息
              this.nextShow = true
              this.$refs.stable.loadData({}, this.generationInfo)
            } else { // 如果是单表查询
              var dataBase = this.form.getFieldValue('dataBase')
              var tableName = this.form.getFieldValue('tableName')
              return query('/generator/code/generatormd/tableInfo/' + dataBase + '?tableName=' + tableName, 'GET', {}, {})
                .then(res => {
                  this.nextShow = true// 显示表格
                  this.$refs.stable.localDataSource = res.result.data// 赋值
                  this.$refs.stable.localPagination.pageSize = res.result.data.length// 改变表格默认大小
                  this.$refs.stable.localLoading = false // 取消加载效果
                })
            }
          }
        } else if (value === '2') { // 代码生成
          this.allMsg = Object.assign({}, this.form.getFieldsValue())// 表单数据
          this.allMsg.table = Object.assign({}, this.$refs.stable.localDataSource)// 列表数据集合
          this.allMsg.methods = this.methods// 生成的方法集合
          console.info(this.allMsg)
          // 生成代码
          this.actionParam = {
            'url': '/generator/code/generatormd/start',
            'action': 'post',
            'parameter': {},
            'data': this.allMsg
          }
          return download(this.actionParam).then(res => {
            this.downloadfile(res, this.allMsg.gName)// 下载生成代码
          })
        } else { // 返回按钮
          this.nextShow = false
        }
      })
    },
    // 配置信息联动
    configChange (value) {
      this.configInfo.forEach(item => {
        if (item.id === value) {
          this.form.setFieldsValue({
            javaPath: item.javaPath,
            vuePath: item.vuePath,
            serverName: item.serverName
          })
        }
      })
    },
    // 数据库信息联动
    dataBaseChange (value) {
      this.tables = []
      return query('/generator/code/generatormd/tables/' + value, 'GET', {}, {})
        .then(res => {
          this.tables = res.result.data
          this.form.setFieldsValue({ 'tableName': this.tables[0].tableName })// 默认选中第一个
        })
    },
    // 生成类型联动
    generationTypeChange (obj) {
      if (obj.target.value === 'some') {
        this.generationTypeIf = true
      } else {
        this.generationTypeIf = false
      }
    },
    // 查询条件选择
    queryCheck (index, e) {
      this.$refs.stable.localDataSource[index].queryIf = e.target.checked// 更改列表选中状态
    },
    // 列表条件选择
    listCheck (index, e) {
      this.$refs.stable.localDataSource[index].listIf = e.target.checked// 更改列表选中状态
    },
    // 列表编辑
    colChange (index, e) {
      this.$refs.stable.localDataSource[index].comments = e.target.value// 更改列表选中状态
    },
    // 字段设置页面
    columnConfig (index, record, text) {
      this.columnConfigIndex = index// 设置行号
      this.columnsConfig = this.$refs.stable.localDataSource[index]
      this.columnVisible = true // 弹出字段配置页面
    },
    // 确认
    handleOk () {
      // 必填校验
      this.modalform.validateFields((err, values) => {
        if (!err) {
          this.$refs.stable.localDataSource[this.columnConfigIndex].columnQueryType = this.columnsConfig.columnQueryType// 查询条件类型
          this.$refs.stable.localDataSource[this.columnConfigIndex].selectSource = this.columnsConfig.selectSource// 下拉框数据源
          this.columnVisible = false // 关闭页面
        }
      })
    },
    // 可编辑字段赋值
    onCellChange (index, value) {
      this.$refs.stable.localDataSource[index].comments = value// 更改列表选中状态
    },
    // 复选框改变
    onCheckBoxChange (checkedValues) {
      this.methods = checkedValues
    },
    // 下载
    downloadfile (data, filename) {
      if (!data) {
        return
      }
      const url = window.URL.createObjectURL(new Blob([data], { type: 'application/zip' }))
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      // download 属性定义了下载链接的地址而不是跳转路径
      link.setAttribute('download', filename + '.zip')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }
  }
}
</script>
<style scoped>
.form-row{
  margin-top:5px;
}
</style>
